package cn.itsource.controller;

import cn.itsource.domain.User;
import cn.itsource.query.Query;
import cn.itsource.service.UserService;
import cn.itsource.util.AjaxResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //注意前端地址：http://localhost:8080/user - get
    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }


    //注意前端地址：http://localhost:8080/user/1 - get
    @GetMapping("/{id}")
    public User findOne(@PathVariable("id") Long id) {
        return userService.findOne(id);
    }


    //注意前端地址：http://localhost:8080/user - put - {}
    @PutMapping
    public AjaxResult addorUpdate(@RequestBody User user, HttpServletRequest request) {

        try {
            if (user.getId() == null) {//添加操作
                userService.add(user);
            } else {

                User userlogin = (User) request.getSession().getAttribute("USER_IN_SESSION");
                user.setSalt(userlogin.getSalt());
                user.setPassword(userlogin.getPassword());
                userService.update(user);

            }
            //如果成功
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }

    //注意前端地址：http://localhost:8080/user/1 - delete

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            userService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }

    //分页+模糊查询
    @PostMapping
    public PageInfo<User> pageQuery(@RequestBody Query query) {

        //前端接收参数：total，list
        return userService.pageQuery(query);
    }

    //批量删除
    @PatchMapping
    public AjaxResult patchdel(@RequestBody Long[] ids) {
        try {
            userService.patchdel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }
}
